package com.shycloud.mido.member.service.impl;

import java.util.Map;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.member.api.entity.OptHardwareSale;
import com.shycloud.mido.member.api.feign.MasterFeignService;
import com.shycloud.mido.member.api.vo.MemberVO;
import com.shycloud.mido.member.mapper.OptHardwareSaleMapper;
import com.shycloud.mido.member.service.MemberServiceV2;
import com.shycloud.mido.member.service.OptHardwareSaleService;

import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class OptHardwareSaleServiceImpl extends ServiceImpl<OptHardwareSaleMapper, OptHardwareSale> implements OptHardwareSaleService {

	/** redis 工具类 */
	private RedisTemplate redisTemplate;
	/** 用户模块service */
	private MemberServiceV2 memberService;
	/** 纠错大师激活模块 service feign */
	private MasterFeignService masterFeignService;

	@Override
	public String registerAndActivate(Map<String, String> requestMap) {

		//手机号 - 作为查询的 username
		String phone = requestMap.get("phone");
		if (phone == null) {
			throw new BusinessException("手机号不能为空，参数名为'phone'");
		}
		//验证码
		String code = requestMap.get("code");
		if (code == null) {
			throw new BusinessException("验证码不能为空，参数名为'code'");
		}
		//udid
		String udid = requestMap.get("udid");
		if (udid == null) {
			throw new BusinessException("udid不能为空，参数名为'udid'");
		}
		//激活码
		String actCode = requestMap.get("actCode");
		if (actCode == null) {
			throw new BusinessException("激活码不能为空，参数名为'actCode'");
		}

		//判断验证码是否正确
		String resultCode = (String) redisTemplate.opsForValue().get(CommonConstants.DEFAULT_CODE_KEY + "SMS@" + phone);
		if (resultCode == null) {
			throw new BusinessException("验证码已过期");
		}
		if (!resultCode.equals(code)) {
			throw new BusinessException("验证码不正确");
		}

		//注册用户
		memberService.register(phone, "123456", null);

		MemberVO memberByPhone = memberService.getMemberByPhone(phone);

		requestMap.put("memberId", memberByPhone.getId());

		//开通硬件权限
		R result = masterFeignService.addActivationH5(requestMap);

		if (result.getCode() == 1) {
			throw new BusinessException(result.getMsg());
		}

		//查询到期日期
		String endTime = masterFeignService.getMsterEndTime(memberByPhone.getId());

		return endTime;
	}
}
